
package com.jf.cloud.service.sysmanager.remote.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jf.cloud.service.sysmanager.constant.UserConstant;
import com.jf.cloud.service.sysmanager.dao.*;
import com.jf.cloud.service.sysmanager.entity.*;
import com.jf.cloud.service.sysmanager.support.entity.Result;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jf.cloud.service.sysmanager.common.base.OPaging;
import com.jf.cloud.service.sysmanager.common.db.Query;
import com.jf.cloud.service.sysmanager.common.taglib.Paging;
import com.jf.cloud.service.sysmanager.common.util.StringUtil;
import com.jf.cloud.service.sysmanager.constant.UserMatchConstant;
import com.jf.cloud.service.sysmanager.handler.TokenHandler;
import com.jf.cloud.service.sysmanager.support.web.BaseController;

/**
 * 赛事资金结算控制器
 * 
 * @author 代码机1.0 创建时间：2018-03-31
 */
@Controller
@RequestMapping("/appPubgMatchSettlement")
public class AppPubgMatchSettlementController extends BaseController {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(AppPubgMatchSettlementController.class);

	@Resource
	private IPubgUserService pubgUserService;

	@Resource
	private IPubgMatchService pubgMatchService;

	@Resource
	private TokenHandler tokenHandler;
	
	@Resource
	private IPubgUserMatchService pubgUserMatchService;

	@Resource
	private IPubgMatchSettlementService pubgMatchSettlementService;
	
	/**
	 * 俱乐部服务
	 */
	@Resource
	private IPubgClubService pubgClubService;

	/**
	 * 战队服务
	 */
	@Resource
	private IPubgTeamService pubgTeamService;

	/**
	 * 我的战绩
	 *
	 * @author 高冬冬 创建时间：2018-04-08
	 */
	@ResponseBody
	@RequestMapping("/myMatchSettlement")
	public Result<Map<String, Object>> myMatchSettlement(OPaging<PubgMatchSettlement> page, HttpServletRequest request, HttpServletResponse response) {
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
		result.setCode(-1);
		result.setMessage("获取我的战绩列表失败！");
		try {
			String token = getParamValueString(request, "token");
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
				return result;
			}
			// 每页数据条数
			int limit = getParamValueInteger(request, "limit", 50);
			page.setLimit(limit);

			// 第几页
			int offset = getParamValueInteger(request, "offset", -1);
			if (offset > 0) {
				page.setOffset((offset-1)*limit);
			}

			// 排序方式
			String order = getParamValueString(request, "order");
			if (StringUtil.isNotEmpty(order)) {
				page.setOrder(order);
			}

			// 排序字段
			String sort = getParamValueString(request, "sort");
			if (StringUtil.isNotEmpty(sort)) {
				page.setSort(sort);
			}

            PubgUser pubgUser = pubgUserService.findByPK(Long.parseLong(userId));
			if (pubgUser.getUserRole() != UserConstant.USER_ROLE_10.getId().intValue()) {
				result.setCode(0);
				result.setData(new HashMap<>());
				result.setMessage("您不是普通队员！");
			    return result;
            }
			page.getWm().put("USER_ID", pubgUser.getRowId());
			page.getWm().put("_NOT_NULL$RESULT_CONFIRM_ID", "_NOT_NULL$RESULT_CONFIRM_ID");//已发放奖励
			Double obtainAwardSum = 0d;
            //返回的数据集合
			Map<String, Object> data = new HashMap<String, Object>();
			Map<String,String> columns = new HashMap<String,String>();
			columns.put("ROW_ID", "rowId");
			columns.put("MATCH_NAME", "matchName");
			columns.put("OBTAIN_RANK", "obtainRank");
			columns.put("OBTAIN_AWARD", "obtainAward");
			columns.put("RESULT_CONFIRM_TIME", "resultConfirmTime");

            Paging<PubgMatchSettlement> pageTemp = pubgMatchSettlementService.findPage(columns,page);
            if (pageTemp != null && pageTemp.getDataList().size() > 0) {
                for (PubgMatchSettlement pubgMatchSettlement:pageTemp.getDataList()) {
					if (pubgMatchSettlement.getObtainAward() != null) {
						obtainAwardSum += pubgMatchSettlement.getObtainAward();
					}
                }
            }
            //查询用户报名成功的比赛数量(参赛总数)
			columns = new HashMap<String,String>();
			columns.put("ROW_ID", "rowId");
            Query query = new Query();
			query.put("USER_ID", pubgUser.getRowId());
			query.put("USER_STATE", UserMatchConstant.USER_MATCH_20.getId());
			List<PubgUserMatch> userMatchList = pubgUserMatchService.findList(columns, query);
			if (userMatchList != null && userMatchList.size() > 0) {
				data.put("userMatchSum",userMatchList.size());
			} else {
				data.put("userMatchSum",0);
			}
			//查询用户吃鸡总次数
			columns = new HashMap<String,String>();
			columns.put("ROW_ID", "rowId");
			query = new Query();
			query.put("USER_ID", pubgUser.getRowId());
			query.put("_NOT_NULL$RESULT_CONFIRM_ID", "_NOT_NULL$RESULT_CONFIRM_ID");
			query.put("OBTAIN_RANK", "1");//第一名
			List<PubgMatchSettlement> cjList = pubgMatchSettlementService.findList(columns, query);
			if (cjList != null && cjList.size() > 0) {
				data.put("eatChickenSum",cjList.size());
			} else {
				data.put("eatChickenSum",0);
			}
			data.put("obtainAwardSum", obtainAwardSum);
			data.put("data",pageTemp.getDataList());
			result.setData(data);
			result.setCode(0);
			result.setMessage("获取我的战绩成功！");
		} catch (Exception e) {
			log.error("获取我的战绩出错！", e);
		}
		return result;
	}

	/**
	 * 战绩提交列表
	 *
	 * @author 高冬冬 创建时间：2018-04-11
	 */
	@ResponseBody
	@RequestMapping("/matchSettlementList")
	public Result<List<Map<String, Object>>> matchSettlementList(HttpServletRequest request, HttpServletResponse response) {
		Result<List<Map<String, Object>>> result = new Result<List<Map<String, Object>>>();
		result.setCode(-1);
		result.setMessage("获取战绩提交列表失败！");
		try {
			String token = getParamValueString(request, "token");
			String userId = tokenHandler.getCommUserInfoByToken(token);
			if (userId == null || userId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
				return result;
			}

			PubgUser pubgUser = pubgUserService.findByPK(Long.parseLong(userId));
			if (pubgUser.getUserRole() != UserConstant.USER_ROLE_20.getId().intValue() && pubgUser.getUserRole() != UserConstant.USER_ROLE_30.getId().intValue()) {
				result.setCode(0);
				result.setData(new ArrayList<Map<String, Object>>());
				result.setMessage("您不是俱乐部部长/战队队长！");
				return result;
			}
			String nickName = getParamValueString(request, "nickName", "");//队员名称
			Integer matchId = getParamValueInteger(request, "matchId", -1);//赛事ID
			if (matchId == null || matchId == -1) {
				result.setMessage("请选择赛事！");
				return result;
			}
			//查俱乐部
			Map<String,String> columns = new HashMap<String,String>();
			columns.put("ROW_ID", "rowId");
			Query query = new Query();
			query.put("_LIKE$MINISTER_ID", pubgUser.getRowId() + ",");
			PubgClub pubgClub = this.pubgClubService.find(columns, query);
			//查战队
			columns = new HashMap<String,String>();
			columns.put("ROW_ID", "rowId");
			columns.put("CLUB_ID", "clubId");
			query = new Query();
			query.put("_LIKE$CAPTAIN_ID", pubgUser.getRowId() + ",");
			PubgTeam pubgTeam = this.pubgTeamService.find(columns, query);
			if (pubgClub == null && pubgTeam == null) {
				result.setCode(0);
				result.setData(new ArrayList<Map<String, Object>>());
				result.setMessage("您不是俱乐部部长/战队队长！");
				return result;
			}
			//查赛事
			Long clubId = null;//俱乐部ID
			if (pubgClub != null) {
				clubId = pubgClub.getRowId();
			} else if (pubgTeam != null) {
				clubId = pubgTeam.getClubId();
			}
			columns = new HashMap<String,String>();
			columns.put("ROW_ID", "rowId");
			query = new Query();
			query.put("ROW_ID", matchId);
			query.put("CLUB_ID", clubId);
			PubgMatch pubgMatch = this.pubgMatchService.find(columns, query);
			if (pubgMatch == null) {
				result.setMessage("只能查看俱乐部下的赛事！");
				return result;
			}
			query = new Query();
			query.put("pum.CLUB_ID", clubId);
			query.put("pum.MATCH_ID", matchId);
			//返回的数据集合
			List<Map<String, Object>> dataList = pubgMatchSettlementService.findMatchSettlementList(query, nickName);
			result.setData(dataList);
			result.setCode(0);
			result.setMessage("获取战绩提交列表成功！");
		} catch (Exception e) {
			log.error("获取战绩提交列表出错！", e);
		}
		return result;
	}
	
	/**
	 * 确认战绩页面列表数据
	 * 
	 * @author 朱建文 创建时间：2018年4月11日 下午5:06:57
	 */
	@ResponseBody
	@RequestMapping("/confirmMatchResultPageList")
	public Result<Map<String, Object>> confirmMatchResultPageList(Long matchId, HttpServletRequest request){
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
		result.setCode(-1);
		result.setMessage("更新赛事状态失败！");
		try {

			// 验证token
			String token = getParamValueString(request, "token");
			String optId = tokenHandler.getCommUserInfoByToken(token);
			if (optId == null || optId.trim().length() == 0) {
				result.setCode(-2);
				result.setMessage("请重新登陆！");
			    return result;
			}

			// 验证操作者身份
			Query query = new Query();
			query.put("_LIKE$MINISTER_ID", optId + ",");
			PubgClub pubgClub = this.pubgClubService.find(query);
			if (pubgClub == null) {
				result.setMessage("您当前还不是部长！");
				return result;
			}
			
			// 验证赛事是否存在
			PubgMatch pubgMatch = this.pubgMatchService.findByPK(matchId);
			if (pubgMatch == null) {
				result.setMessage("赛事不存在！");
				return result;
			}
			
			// 验证操作者与赛事的关系
			if (!pubgMatch.getClubId().equals(pubgClub.getRowId())) {
				result.setMessage("您无权操作该赛事！");
				return result;
			}
			
			Map<String, Object> dataMap = this.pubgMatchSettlementService.getMatchSettlementAuditList(matchId, pubgClub.getRowId());
			result.setCode(0);
			result.setData(dataMap);
			result.setMessage("获取列表数据成功！");
		} catch (Exception e) {
			log.error("获取确认战绩页面列表数据出错！", e);
		}
		return result;
	}
}
